<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Token;
use app\common\model\card\Dealer as DealerModel;
use app\common\model\card\Entity;
use app\common\model\card\entity\Site;
use app\common\model\card\Entitylog;
use app\common\model\card\Transferlog;
use app\common\model\Member;
use app\common\model\Order;
use app\common\model\Regionserviceuser;
use Exception;
use fast\Random;
use think\Db;
use think\Validate;

/**
 * 卡经销商接口
 */
class Dealer extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token=Token::get($token);
        if($token["type"]!=3) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
        /*判断当前账号身份 end*/
        $user =DealerModel::get($this->auth->id);
        if(empty($user)) $this->error("卡经销商不存在");
        if(empty($user["status"])) $this->error("卡经销商审核中");
        if($user["status"]==2) $this->error("卡经销商已被驳回：".$user["remark"]);
        if($user["status"]==3) $this->error("卡经销商已被禁用");
    }

    /**
     * 修改资料
     * */
    public function dealerUpdate()
    {
        if(!$this->request->param("name")) $this->error("请填写卡经销商名称");
        $params = $this->request->param();
        $row=DealerModel::get($this->auth->id);
        if(empty($row)) $this->error("卡经销商不存在");
        Db::startTrans();
        try {
            $ret=$row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success(__('修改成功'));
        } else {
            $this->error("修改失败".$this->auth->getError());
        }
    }
    /**
     * 获取推广码
     * */
    public function getPromotionCode()
    {
        $user=$this->auth->getUser();
        $code=[
            "promotion_code"=>$user["promotion_code"],
            "promotion_url"=>$user["promotion_url"],
        ];
        if(empty($user["promotion_code"]) || empty($user["promotion_url"])){
            $mycardModel = new \app\common\model\Merchant();
            $code=$mycardModel->getPromotionCode($this->auth->id,2);//生成二维码
        }
        $this->success("成功",$code);
    }
    /**
     *分销订单
     * */
    public function orderList()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $order = Order::field("id,name,agent_commission,price,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime,order_no")
            ->where(["status" => '1', "agent_id" => $this->auth->id,"agent_type"=>'3']);
        $order_sum = Order::field("id,name,agent_commission,price,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime,order_no")
            ->where(["status" => '1', "agent_id" => $this->auth->id,"agent_type"=>'3']);
        if ($this->request->param("day")) {
            $day = $this->request->param("day");
            $day_field = "today";
            if ($day == 2) $day_field = "month";
            if ($day == 3) $day_field = "year";
            $order = $order->whereTime("createtime", $day_field);
            $order_sum = $order_sum->whereTime("createtime", $day_field);
        } else {
            if ($this->request->param("start_time")) {
                $order = $order->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
                $order_sum = $order_sum->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
            }
        }
        $list=$order
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])->toArray();
        $list["all_money"]=$order_sum->sum("agent_commission").'';
        $this->success("成功", $list);
    }
    /**
     * 获取实体卡名称
     * */
    public function getEntityName()
    {
        $list=Entitylog::field("card_entity_id id,card_entity_site_id")->where(["card_dealer_id"=>$this->auth->id]);
        if ($this->request->param('type') && $this->request->param('type') == 1)
        {
            //待接收
            $list=$list->where(["transfer_data"=>'2']);
        }else{
            $list=$list->where(["transfer_data"=>'1']);
        }
        $list=$list->group("card_entity_id")->select();
        if(!empty($list)){
            foreach ($list as &$v){
                $name=Site::field("kabaw_name")->where(["id"=>$v["card_entity_site_id"]])->find();
                $v["name"]=$name["kabaw_name"]??'';
                $v->visible(['id', 'name']);
            }
        }
        $this->success("成功", $list);
    }
    /**
     * 实体卡列表
     * */
    public function entityList()
    {
        if(!$this->request->param("id")) $this->error("实体卡id为空");
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $field="id,exchange_number,status";
        if(!$this->request->param('type'))$field.=",code";
        $list = Entitylog::field($field)//,code
            ->where(["card_dealer_id"=>$this->auth->id,"card_entity_id"=>$this->request->param("id")]);
        if ($this->request->param('type') && $this->request->param('type') == 1)
        {
            //待接收
            $list=$list->where(["transfer_data"=>'2']);
        }else{
            $list=$list->where(["transfer_data"=>'1']);
        }
        $list=$list->paginate(20, '', ['page' => $page, 'list_rows' => 20])->toArray();
        $this->success("成功", $list);
    }

    /**
     * 接收、拒绝卡
     * */
    public function receiveEntity()
    {
        if(!$this->request->param("id")) $this->error("卡包id为空");
        $id=$this->request->param("id");
        $status = !$this->request->param('status') ? 1 : $this->request->param('status');//1接收 2 拒绝
        $list = Entitylog::field("id")
            ->where(["card_dealer_id"=>$this->auth->id,"transfer_data"=>'2',"card_entity_id"=>$id])
            ->find();
        if(empty($list)) $this->error("没有待接收的卡");
        Db::startTrans();
        try {
            $log_update=["transfer_data"=>$status];
            if($status==2){
                //拒绝
                $log=Transferlog::field("card_entity_id,SUM(transfer_num) sum_transfer")
                    ->where(["card_dealer_id"=>$this->auth->id,"transfer_data"=>'0',"card_entity_id"=>$id])
                    ->group("card_entity_id")
                    ->select();
                $update=[];
                if(!empty($log)){
                    $model=new Entity();
                    foreach ($log as $k=>$v){
                        $entity=$model->field("transfer_num")->where(["id"=>$v["card_entity_id"]])->find();
                        $update[$k]=[
                            "id"=>$v["card_entity_id"],
                            "transfer_num"=>$entity["transfer_num"]-$v["sum_transfer"],
                        ];
                    }
                    if(!empty($update)){
                        $model->saveAll($update);
                    }
                }
                $log_update["card_dealer_id"]=0;
                $log_update["transfer_data"]='0';
            }
            Transferlog::where(["card_dealer_id"=>$this->auth->id,"transfer_data"=>'0',"card_entity_id"=>$id])
                ->update(["transfer_data"=>$status,"receive_time"=>time()]);
            if($status==2) $log_update["transfer_data"]='3';
            $res=Entitylog::where(["card_dealer_id"=>$this->auth->id,"transfer_data"=>'2',"card_entity_id"=>$id])
                ->update($log_update);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("成功");
    }


    /**
     * 兑换记录
     * */
    public function exchangeList(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list = Entitylog::field("id,exchange_number,from_unixtime(exchange_time, '%Y-%m-%d %H:%i:%s') createtime")
            ->with(["member"=>function($query){
                $query->withField('nickname');
            },"site"=>function($query){
                $query->withField('kabaw_name');
            }])
            ->where(["card_dealer_id"=>$this->auth->id,"entitylog.status"=>"1"])
            ->paginate(20, '', ['page' => $page, 'list_rows' => 20])->toArray();
        $this->success("成功", $list);
    }


    //2023-10-9 新增  start
    /**
     * 我的下级
     * */
    public function belowList(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list = Member::field("id,nickname,avatar")
            ->where(["agent_id"=>$this->auth->id,"agent_data"=>"2"])
            ->paginate(20, '', ['page' => $page, 'list_rows' => 20])->toArray();
        $this->success("成功", $list);
    }
    /**
     * 下级购买记录
     * */
    public function belowPayList(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        if(!$this->request->param("member_id")) $this->error("id为空");
        $list=Order::field("id,name,agent_commission,price,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime,order_no")
            ->where(["status" => '1', "agent_id" => $this->auth->id,"agent_type"=>'3',"member_id"=>$this->request->param("member_id")])
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])->toArray();
        $this->success("成功", $list);
    }
    //2023-10-9 新增  end

}
